﻿using BaseProject.Application.Interfaces;
using BaseProject.Domain.Enums;
using BaseProject.Domain.Models;
using BaseProject.Domain.Repositories;
using BaseProject.Infrastructure.Helpers;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace BaseProject.Application.Implementation
{
    public class UserServiceImpl : BaseServiceImpl<User>, IUserService
    {
        private readonly IUserRepository _userRepository;

        public UserServiceImpl(IUserRepository userRepository)
            : base(userRepository)
        {
            this._userRepository = userRepository;
        }

        /// <summary>
        /// 根据手机获取用户
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public async Task<User> GetUserByMobile(string mobile)
        {
            var list = await _userRepository.GetList();
            var user = list.Any() ? list.FirstOrDefault(s => s.Mobile == mobile) : null;
            return user;
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task<UserLoginStatus> Login(string mobile, string password)
        {
            var user = await GetUserByMobile(mobile);
            if (user == null)
                return UserLoginStatus.UserNotExist;
            if (user.IsDelete)
                return UserLoginStatus.Deleted;
            if (user.Status == UserStatus.Disable)
                return UserLoginStatus.Disable;
            password = UtilHelper.Md5(password);
            if (string.IsNullOrEmpty(user.Password))
                return UserLoginStatus.WrongPassword;
            if (user.Password.ToLower() != password.ToLower())
                return UserLoginStatus.WrongPassword;

            //更新登录时间
            user.Mtime = DateTime.Now;
            await _userRepository.Update(user);
            return UserLoginStatus.Successful;
        }
    }
}